<?php

namespace app\admin\model\wanlshop;

use think\Db;
use think\Model;


class Giftlog extends Model
{

    

    

    // 表名
    protected $name = 'wanlshop_giftlog';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;


    const STATUS_NORMAL=1;//未兑奖
    const STATUS_DISABLE=2;//已兑奖

    /**
     * 获取状态列表
     * */
    static public function getTrueStatusList($type=2,$value=1){
        $data= [
            self::STATUS_NORMAL=>'未兑奖',
            self::STATUS_DISABLE=>'已兑奖',
        ];
        if($type==1){
            return isset($data[$value])?$data[$value]:'';
        }else{
            return $data;
        }
    }

    /**
     * 抽奖
     * */
    static public function getGift($userInfo,$get_gift_point){
        $re_data=[
            'code'=>204,
            'msg'=>'抽奖失败',
            'data'=>[],
        ];
        $gift_list=Gift::where(['status'=>Gift::STATUS_NORMAL])->select();
        if(!is_array($gift_list)){
            $gift_list=$gift_list->toArray();
        }
        foreach ($gift_list as $k=>$v){
//            $v['img_path']=get_img_path($v['img']);
            $gift_list[$k]=$v;
        }
        $max=0;
        foreach ($gift_list as $k=>$v){
            $max+=$v['rate'];
            $chou_list[]=[
                'v'=>$max,
                'id'=>$v['id'],
            ];
        }
        $rand=rand(1,$max);
        $zone=0;
        $zhong=0;
        foreach ($chou_list as $k=>$v){
            if($rand<=$v['v']){
                $zhong=$v['v'];
                $zone=$v['id'];
                break;
            }
        }
        $gift_list=array_column($gift_list,null,'id');
        if(!isset($gift_list[$zone])){
            $re_data['msg']='抽奖失败，请重试1';
            return $re_data;
        }
        $data=$gift_list[$zone];
        //记录抽奖
        $log=[
            'user_id'=>$userInfo['id'],
            'gift_id'=>$data['id'],
            'create_time'=>time(),
            'name'=>$data['name'],
            'img'=>$data['img'],
            'type'=>$data['type'],
            'value'=>$data['value'],
            'status'=>GiftLog::STATUS_NORMAL,
            'rand'=>$rand,
            'zhong'=>$zhong,
            'max'=>$max,
            'log'=>serialize($gift_list),
        ];
        //增加用户记录
        $log1=[
            'user_id' => $userInfo['id'],
            'before' => $userInfo['yuanbao'],
            'after' => bcsub($userInfo['yuanbao'],$get_gift_point,2),
            'money' => -$get_gift_point, // 操作金额
            'memo' => '抽奖扣除'.$get_gift_point, // 备注
            'type' =>  'gift', // 类型
            'service_ids' =>'' // 业务ID
        ];
        $res=false;
        Db::startTrans();
        try{
            //写抽奖记录
            $log_id=(new Giftlog())->insertGetId($log);
            $data['log_id']=$log_id;

            $re1=true;
            $re2=true;
            //扣除抽奖积分
            if($get_gift_point){
                //更新用户金额
                $re2 = \app\common\model\User::where(['id'=>$log1['user_id']])->setDec('yuanbao',$get_gift_point);
                // 支付日志
                $re1= model('app\common\model\MoneyLog')->create($log1);
            }
            if($log_id && $re1&& $re2){
                $res=true;
                Db::commit();
            }else{
                Db::rollback();
            }
        }catch (\Exception $exception){
            Db::rollback();
        }
        if(!$res){
            $re_data['msg']='抽奖失败，请重试';
            return $re_data;
        }
        return [
            'code'=>200,
            'msg'=>'抽奖成功',
            'data'=>$data,
        ];
    }




    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'status_text',
        'delete_time_text',
        'type_text'
    ];
    

    
    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2')];
    }

    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2')];
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delete_time']) ? $data['delete_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeleteTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function gift()
    {
        return $this->belongsTo('Gift', 'gift_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function goods()
    {
        return $this->belongsTo('Goods', 'value', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
